package cuit.demo.controller;

import cuit.demo.Entity.User;
import cuit.demo.service.MyService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/personalhomepage")
public class ReviseUserController {

    @Autowired
    private MyService myService;

    // 显示修改用户信息页面
    @GetMapping("/xianshiuser")
    public String showReviseUserPage(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user!= null) {
            model.addAttribute("user", user);
            return "reviseuser";
        } else {
            return "redirect:/personalhomepage";
        }
    }

    // 处理用户信息修改提交
    @PostMapping("/reviseuser")
    public String reviseUser(@RequestParam int userId,
                             @RequestParam("username") String username,
                             @RequestParam("password") String password,
                             @RequestParam("gender") String gender,
                             @RequestParam("phone") String phone,
                             @RequestParam("email") String email,
                             Model model,HttpSession session) {
        User user = (User)session.getAttribute("user");
        User existingUser = myService.findUserById(userId);
        if (existingUser!= null) {
            existingUser.setUserid(user.getUserid());
            existingUser.setUsername(username);
            existingUser.setUserpwd(password);
            existingUser.setUsersex(gender);
            existingUser.setPhone(phone);
            existingUser.setEmail(email);
            myService.updateUser(existingUser);
            model.addAttribute("message", "用户信息修改成功");
        } else {
            model.addAttribute("error", "用户不存在，无法修改信息");
        }
        return "redirect:/personalhomepage";
    }
}